package com.yuchen.ishop.web.app;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.yuchen.core.jdbc.BaseDao;
import com.yuchen.ishop.entity.Buyer;
import com.yuchen.ishop.entity.Seller;
import com.yuchen.ishop.service.buyer.BuyerRestClient;
import com.yuchen.ishop.service.seller.SellerRestClient;
import com.yuchen.ishop.web.BaseAction;
import com.yuchen.utils.security.PasswordUtils;

/**
 * 注册
 */
@Controller
public class RegisterAction extends BaseAction {

    private final static Logger LOG = Logger.getLogger(RegisterAction.class);

    @Autowired
    private BaseDao baseDao;

    @Autowired
    private SellerRestClient sellerRestClient;
    
    @Autowired
    private BuyerRestClient buyerRestClient;


    @RequestMapping(value = "/validateAjax")
    @ResponseBody
    public Map validateAjax(HttpServletRequest request){
        Map<String,Object> params = convertParameterMap(request.getParameterMap());
        StringBuilder sql = new StringBuilder();
        sql.append("from ").append(params.get("table")).append(" where ");
        for(Map.Entry entry : params.entrySet()){
            if("table".equals(entry.getKey())) {
                continue;
            };
            sql.append(entry.getKey()).append("=@").append(entry.getKey());
        }
        int count = baseDao.count(sql.toString(),params);
        Map map = new HashMap();
        if(count > 0){
            map.put("error","已存在");
        }else{
            map.put("ok","");
        }
        return map;
    }


    @RequestMapping(value = "/sellerRegister",method = RequestMethod.POST)
    public String sellerRegister(@Valid Seller seller, BindingResult result,HttpServletRequest request,RedirectAttributes redirectAttributes){
        if(doCRSF(request)){
            redirectAttributes.addFlashAttribute("flash",errorJson("非法CRSF请求！"));
            return "redirect:/error.htm";
        }
        if(result.hasErrors()){
            redirectAttributes.addFlashAttribute("flash",errorJson("非法请求！"));
            return "redirect:/error.htm";
        }
        Map map = PasswordUtils.genMD5Str(seller.getPassword());
        seller.setSalt((String) map.get("salt"));
        seller.setPassword((String) map.get("password"));
        seller.setState(1l);
        seller.setIdentification(0l);
        seller.setCreateTime(getTime());
        sellerRestClient.insert(seller);
        redirectAttributes.addFlashAttribute("register","success");
        redirectAttributes.addFlashAttribute("tab",2);
        return "redirect:/goLogin.htm";
    }

    private String goReg(int tab,RedirectAttributes redirectAttributes){
        redirectAttributes.addFlashAttribute("flash",errorJson("用户名或密码错误！"));
        redirectAttributes.addFlashAttribute("tab",tab);
        return "redirect:/goRegister.htm";
    }
    
    @RequestMapping(value = "/buyerRegister",method = RequestMethod.POST)
    public String buyerRegister(@Valid Buyer buyer, BindingResult result,HttpServletRequest request,RedirectAttributes redirectAttributes){
        if(doCRSF(request)){
            redirectAttributes.addFlashAttribute("flash",errorJson("非法CRSF请求！"));
            return "redirect:/error.htm";
        }
        if(result.hasErrors()){
            redirectAttributes.addFlashAttribute("flash",errorJson("非法请求！"));
            return "redirect:/error.htm";
        }
        Map map = PasswordUtils.genMD5Str(buyer.getPassword());
        buyer.setSalt((String) map.get("salt"));
        buyer.setPassword((String) map.get("password"));
        buyer.setState((short)1);
        buyer.setIdentification((short)0);
        buyer.setCreateTime(getTime());
        buyerRestClient.insert(buyer);
        redirectAttributes.addFlashAttribute("register","success");
//        redirectAttributes.addFlashAttribute("tab",1);
        return "redirect:/goLogin.htm";
    }
}
